<template>
    <public-title @change-v="changeV" @changeShowStatus="changeShowStatus" :keyType="keyType" :user-id="userId" />
    <div class="item-three" style="display: flex; justify-content: center" v-if="status">
        <div style="width: 15%; text-align: center">
            <div>
                <template v-if="getTime(maxInfo)?.h > 0">
                    <span style="font-size: 25px"> {{ getTime(maxInfo)?.h }}</span>
                    <span style="color: #aa9db6">小时</span>
                </template>
                <span style="font-size: 25px"> {{ getTime(maxInfo)?.m }}</span>
                <span style="color: #aa9db6">分钟</span>
            </div>
            <div style="color: #aa9db6">{{ type == 1 ? '深睡睡眠时长' : '日均深睡时长' }}</div>
        </div>
        <div style="width: 15%; text-align: center">
            <div>
                <template v-if="getTime(minInfo)?.h > 0">
                    <span style="font-size: 25px"> {{ getTime(minInfo)?.h }}</span>
                    <span style="color: #aa9db6">小时</span>
                </template>
                <span style="font-size: 25px"> {{ getTime(minInfo)?.m }}</span>
                <span style="color: #aa9db6">分钟</span>
            </div>
            <div style="color: #aa9db6">{{ type == 1 ? '浅睡睡眠时长' : '日均浅睡时长' }}</div>
        </div>
        <div style="width: 15%; text-align: center">
            <div>
                <template v-if="getTime(middleInfo)?.h > 0">
                    <span style="font-size: 25px">{{ getTime(middleInfo)?.h }}</span>
                    <span style="color: #aa9db6">小时</span>
                </template>
                <span style="font-size: 25px">{{ getTime(middleInfo)?.m }}</span>
                <span style="color: #aa9db6">分钟</span>
            </div>
            <div style="color: #aa9db6">{{ type == 1 ? '睡眠总时长' : '日均睡眠总时长' }}</div>
        </div>
    </div>
    <div v-if="status && !isEmpty" ref="chartRef" style="min-height: 300px; width: 100%"></div>
    <template v-if="status && isEmpty">
        <div style="min-height: 300px; width: 100%; display: flex; align-items: center; justify-content: center">
            <a-empty />
        </div>
    </template>

    <BasicTable v-if="!status" :key="refresh" :columns="sleepColumns" :api="querySleepStatisticsPageApi" :api-params="apiParams" />
</template>
<script setup lang="ts">
    import PublicTitle from '/@/components/secondaryScreen/secondMap/components/userInfoModal/publicTitle.vue';
    import { nextTick, onMounted, ref } from 'vue';
    import * as echarts from 'echarts';
    import BasicTable from '/@/components/secondaryScreen/secondMap/components/basicTable/BasicTable.vue';
    import { querySleepStatisticsApi, querySleepStatisticsPageApi } from '/@/components/secondaryScreen/secondMap/secondMapApi.ts';
    import { propTypes } from '/@/utils/propTypes';
    import dayjs from 'dayjs';
    import { message } from 'ant-design-vue';
    import { sleepColumns } from '/@/components/secondaryScreen/secondMap/components/userInfoModal/tableColumns.ts';
    import { useChangeTable } from '/@/components/secondaryScreen/secondMap/secondMapHooks.ts';

    const type = ref(1);
    const status = ref<boolean>(true);
    const value = ref(dayjs(new Date()).format('YYYY-MM-DD'));
    const maxInfo = ref();
    const middleInfo = ref();
    const minInfo = ref();
    const isEmpty = ref(false);

    const props = defineProps({
        userId: propTypes.string.def(''),
        keyType: propTypes.string.def('4'),
    });
    const { refresh, setRefresh } = useChangeTable();
    const apiParams = ref({
        flag: 0,
        userId: props.userId,
        pageSize: 10,
        pageNo: 1,
    });

    function tableReload() {
        nextTick(() => {
            apiParams.value = {
                flag: 0,
                userId: props.userId,
                pageSize: 10,
                pageNo: 1,
            };
            setRefresh();
        });
    }

    let echart = null;

    function changeV(j: any) {
        type.value = j.type;
        value.value = j.value;
        isEmpty.value = false;
        initF();
    }

    function initF() {
        if (status.value) {
            echart && echart.clear();
            initEchart();
        } else {
            tableReload();
        }
    }

    function changeShowStatus(s: boolean) {
        status.value = s;
        if (s) {
            nextTick(() => {
                initEchart();
            });
        }
    }

    const chartRef = ref();

    /**
     *  @type 传入 type = '1' 则不需要要渲染图表
     * */
    async function initEchart() {
        try {
            const { code, result, message: msg } = await querySleepStatisticsApi(getParams());
            maxInfo.value = '';
            middleInfo.value = '';
            minInfo.value = '';
            if (code === 200) {
                isEmpty.value = type.value === 1 ? result.timePeriods.length === 0 : result.viewDataList.length === 0;
                let xArr: any[] = [];
                let yArr: any[] = [];
                let yArr1: any[] = [];
                maxInfo.value = type.value === 1 ? result.maxValue : result.deepSleepTimes ? result.deepSleepTimes : '';
                middleInfo.value = type.value === 1 ? result.total1 : result.deepLightTimes ? result.deepLightTimes : '';
                minInfo.value = type.value === 1 ? result.minValue : result.lightSleepTimes ? result.lightSleepTimes : '';
                // type.value === 1 &&
                //     result.viewDataList.map((item) => {
                //         xArr.push(item.date);
                //         yArr.push(item.value === 1 ? 1 : 0);
                //         yArr1.push(item.value === 2 ? 1 : 0);
                //     });
                type.value !== 1 &&
                    result.viewDataList.map((item) => {
                        const total = (item.value ? item.value : 0) + (item.value1 ? item.value1 : 0);
                        xArr.push(item.date);
                        // let p1 = parseInt(((item.value ? item.value : 0) / total) * 100);
                        // let p2 = parseInt(((item.value1 ? item.value1 : 0) / total) * 100);
                        yArr.push(item.value ? item.value : 0);
                        yArr1.push(item.value1 ? item.value1 : 0);
                    });
                if (type.value === 1) {
                    getZXEchart(result);
                } else {
                    getZEcahrt(xArr, yArr, yArr1);
                }
            } else {
                isEmpty.value = true;
                message.warn(msg);
            }
        } catch {}
    }

    function getZXEchart(res) {
        echart = echarts.init(chartRef.value);
        let xArr: any[] = [];
        let yArr: any[] = [];
        res.timePeriods &&
            res.timePeriods.map((item) => {
                switch (item.flag) {
                    case 1:
                        // 浅睡
                        yArr.push(1);
                        yArr.push(1);
                        break;
                    case 3:
                        // 深睡
                        yArr.push(0);
                        yArr.push(0);
                        break;
                    case 4:
                        // 清醒
                        yArr.push(3);
                        yArr.push(3);
                        break;
                    case 5:
                        // 零星小睡
                        yArr.push(2);
                        yArr.push(2);
                        break;
                }
                xArr.push(dayjs(item.start).format('HH:mm'));
                xArr.push(dayjs(item.end).format('HH:mm'));
            });
        const option = {
            xAxis: {
                type: 'category',
                data: xArr,
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow',
                },
                formatter: function (params) {
                    let tar = params[0];
                    let name = '';
                    switch (tar.value) {
                        case 3:
                            name = '清醒';
                            break;
                        case 2:
                            name = '零星小睡';
                            break;
                        case 1:
                            name = '浅睡';
                            break;
                        case 0:
                            name = '深睡';
                            break;
                    }
                    return xArr[tar.dataIndex] + '<br/>' + name;
                },
            },
            yAxis: {
                show: false,
            },
            series: [
                {
                    data: yArr,
                    type: 'line',
                },
            ],
        };

        echart.setOption(option);
        window.addEventListener('resize', () => {
            echart.resize();
        });
    }

    function getZEcahrt(xArr, yArr, yArr1) {
        echart = echarts.init(chartRef.value);
        const option = {
            title: {},
            legend: {
                textStyle: {
                    color: '#ffffff',
                },
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow',
                },
                formatter: function (params) {
                    let tar1 = params[1];
                    let tar = params[0];
                    // let tar = params[1];
                    // return (tar1.value > 0 ? '短睡' : '长睡') + '<br/>' + tar.seriesName + ' : ' + tar.value;
                    let str = '';
                    if (type.value === 1) {
                        str = xArr[tar.dataIndex] + '<br/>' + (tar1.value > 0 ? '浅睡' : '深睡');
                    } else {
                        str =
                            xArr[tar.dataIndex] +
                            `<div>
                                            <div style="display: flex;justify-content: space-between">
                                                <div>
                                                    深睡：${tar.value ? tar.value : 0}
                                                </div>
                                                <div style="padding-left: 5px">
                                                    分钟
                                                </div>
                                            </div>
                                            <div style="display: flex;justify-content: space-between;">
                                                <div>
                                                    浅睡：${tar1.value ? tar1.value : 0}
                                                </div>
                                                <div style="padding-left: 5px;">
                                                    分钟
                                                </div>
                                            </div>
                                    </div>`;
                    }
                    return str;
                },
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true,
            },
            xAxis: {
                type: 'category',
                splitLine: { show: false },
                data: xArr,
                axisLabel: {
                    color: '#fff',
                },
            },
            yAxis: {
                show: false,
            },
            series: [
                {
                    name: '深睡',
                    type: 'bar',
                    barMaxWidth: '20px',
                    stack: 'a',
                    itemStyle: {
                        borderColor: '#5087ec',
                        borderWidth: 0,
                        color: '#5087ec',
                    },
                    // emphasis: {
                    //     itemStyle: {
                    //         borderColor: '#68bbc4',
                    //         color: '#68bbc4',
                    //     },
                    // },
                    axisLabel: {
                        color: '#fff',
                    },
                    data: yArr,
                },
                {
                    name: '浅睡',
                    barMaxWidth: '20px',
                    stack: 'a',
                    itemStyle: {
                        borderColor: '#85d0dc',
                        borderWidth: 0,
                        color: '#85d0dc',
                    },
                    axisLabel: {
                        color: '#fff',
                    },
                    type: 'bar',
                    data: yArr1,
                },
            ],
        };

        echart.setOption(option);
        window.addEventListener('resize', () => {
            echart.resize();
        });
    }

    function getParams() {
        let params = {
            flag: type.value,
            userId: props.userId,
        };
        switch (type.value) {
            case 1:
                params['dateDay'] = value.value;
                break;
            case 2:
                params['dateWeekStart'] = value.value.substring(0, value.value.indexOf('~') - 1);
                params['dateWeekEnd'] = value.value.substring(value.value.indexOf('~') + 2);
                break;
            case 3:
                params['dateMonth'] = value.value;
                break;
            case 4:
                params['dateYear'] = value.value;
                break;
        }
        return params;
    }

    function getTime(time) {
        if (!time) return { h: 0, m: 0 };
        if (time < 60) return { h: 0, m: time };

        return { h: (time - (time % 60)) / 60, m: time % 60 };
    }

    onMounted(() => {
        initEchart();
    });
</script>
<style scoped lang="less"></style>
